//
//  AppkeyListView.swift
//  sui04mac
//
//  Created by 杨剑 on 2023/11/28.
//

import SwiftUI
import HandyJSON
@Observable
class AppkeyModelData {
    
    var currentAppModelID : Int = UserDefaults.standard.integer(forKey: "AppkeyModelData.currentAppModelID")
    
    var currentAppModel : AppModel? {
        if appModels.isEmpty {
            return nil
        }
//        if currentAppModelID < 0 {
//            return nil
//        }
        if let appmodel = appModels.first(where: {$0.id == currentAppModelID}) {
            return appmodel
        }
        updateCurrentAppModelID(id: appModels.first!.id)
        return appModels.first
    }
    
    func updateCurrentAppModelID(id : Int){
        currentAppModelID = id
        UserDefaults.standard.setValue(currentAppModelID, forKey: "AppkeyModelData.currentAppModelID")
    }
        
    func addAppModels(app : AppModel){
        appModels.append(app)
        if let appstring = app.toJSONString() {
            var list = UserDefaults.standard.stringArray(forKey: "AppkeyModelData.appModels") ?? []
            list.append(appstring)
            UserDefaults.standard.setValue(list, forKey: "AppkeyModelData.appModels")
        }
    }
    func deleteAppModels(id : Int){
        appModels.removeAll { app in
            app.id == id
        }
        var appStrings = [String]()
        for app in appModels {
            if let appString = app.toJSONString() {
                appStrings.append(appString)
            }
        }
        UserDefaults.standard.setValue(appStrings, forKey: "AppkeyModelData.appModels")
    }
    func changeAppModels(changeApp : AppModel){
        appModels.removeAll { app in
            app.id == changeApp.id
        }
        appModels.append(changeApp)
        var appStrings = [String]()
        for app in appModels {
            if let appString = app.toJSONString() {
                appStrings.append(appString)
            }
        }
        UserDefaults.standard.setValue(appStrings, forKey: "AppkeyModelData.appModels")
    }
    var appModels : [AppModel] = loadAppModels()
}
func loadAppModels() -> [AppModel]{
    let list = UserDefaults.standard.stringArray(forKey: "AppkeyModelData.appModels") ?? []
    var apps = [AppModel]()
    for jsonString in  list {
        if let app = JSONDeserializer<AppModel>.deserializeFrom(json: jsonString) {
            apps.append(app)
        }
    }
    return apps
//    if let list = JSONDeserializer<AppModel>.deserializeModelArrayFrom(array: list) as? [AppModel] {
//        return list
//    }
//    return []
}

//    @AppStorage("data.appmodels") var appModels : [AppModel] = [
////        AppModel(id: 0,appkey: "1168171101115760#dabaojian",client_id: "YXA6uUquUL6lEeeIi-vMCP7JJg",client_secret: "YXA6qb6yfKTMOhCdZibj9Q5Z9YNfzoA",cluster: ClusterModel(base_url: "https://a1.easemob.com")),
////        AppModel(id: 1,appkey: "appkey",client_id: "clientid",client_secret: "clients..."),
//    ]//Property wrapper cannot be applied to a computed property


struct AppkeyListView: View {
    @Environment(AppkeyModelData.self) var appModelData
    @Environment(\.openWindow) private var openWindow
    var body: some View {
        @Bindable var md = appModelData
        VStack{
            HStack{
                Spacer()
                Button(action: {
//                    modelData.appModels.append(AppModel(id: modelData.appModels.count,appkey: "test"))
                    openWindow(id: "AddAppPage")
                }, label: {
                    Text("添加一个appkey配置")
                })
            }
            Spacer()
            if appModelData.appModels.isEmpty {
                Button(action: {
//                    modelData.appModels.append(AppModel(id: modelData.appModels.count,appkey: "test"))
                    openWindow(id: "AddAppPage")
                }, label: {
                    Text("至少有一个appkey配置")
                })
            }else{
                List{
                    ForEach(appModelData.appModels){appModel in
                        AppListItem(appModel: appModel)
                    }
                }
            }
            Spacer()

        }
        .padding(0)
            .frame(width: 200)
            .navigationTitle("appkey列表")

    }
    
    struct AppListItem : View {
        
        var appModel : AppModel
        @Environment(AppkeyModelData.self) var appModelData
        var index :Int{
            return appModelData.appModels.firstIndex(where: {$0.id == appModel.id})!
        }
        var body: some View {
//            @Bindable var modelData = modelData
            ZStack{
                if appModel.id == appModelData.currentAppModelID {
                    Color.blue
                }else{
                    Color.white
                }
                
                VStack(alignment: .leading){
                    
//                    HStack(alignment: .top){
//                        Text(appModel.display_name)
//                            .font(.system(size: 15))
//                            .fontWeight(.bold)
//                        Spacer()
//                        Text(appModel.cluster.name)
//                    }
                    Text(appModel.display_name)
                        .font(.system(size: 15))
                        .fontWeight(.bold)
//                        .foregroundStyle(ShapeStyle)
                        
//                    Spacer()
                    Text(appModel.cluster.name)

                    Text(appModel.appkey)
                        .font(.system(size: 12))
                        .lineLimit(2)

                    Text(appModel.cluster.base_url)
                        .font(.system(size: 12))
                        .lineLimit(2)

                    HStack(){
                        Spacer()
                        Button(action: {
                            //https://www.cnblogs.com/lxlx1798/articles/16635055.html
                            copyText()
                        }, label: {
                            Text("复制")
                        })
                            
                        Button(action: {
                            deleteAppConfig()
                            
                        }, label: {
                            Text("删除")
                        }).frame(maxHeight: 100)
                    }
                }
//                HStack{
//                    VStack(alignment:.leading){
//                        Text(appModel.display_name)
//
//                        HStack(alignment: .firstTextBaseline){
//                            Text("appkey:")
//                                .multilineTextAlignment(.leading)
//                                .frame(width: 80)
////                            Text(appModelData.appModels[index].client_id)
//                            Text(appModel.appkey)
//                        }
//    //                    HStack{
//    //                        Text("clientSecret:")
//    //                            .multilineTextAlignment(.leading)
//    //                            .frame(width: 80)
//    //                        Text(modelData.appModels[index].client_secret)
//    //                    }
//                    }.padding(.leading,0)
//                    
//                    Spacer()
//                    
//                }
                .frame(height: 120)
                .padding(0)

            }

            .onTapGesture {
                appModelData.updateCurrentAppModelID(id: appModel.id)
//                appModelData.currentAppModelID = appModel.id
            }
        }
        
        func deleteAppConfig(){
            let temp_index = index;
            if appModelData.currentAppModelID == appModel.id {
                //先删除
                //需要先获取index,否则会有问题,因为index是个计算属性
                
                appModelData.deleteAppModels(id: appModelData.appModels[temp_index].id)
//                appModelData.appModels.remove(at: temp_index)
                //删除之后,判断是否还有
                if temp_index < appModelData.appModels.count {//判断index,是否可选择下一个
                    appModelData.currentAppModelID = appModelData.appModels[temp_index].id
                }else if appModelData.appModels.isEmpty {//如果已经是最后一个,则判断是否为空
                    appModelData.currentAppModelID = -1
                }else{
                    appModelData.currentAppModelID = appModelData.appModels[temp_index - 1].id
                }
            }else{
                appModelData.deleteAppModels(id: appModelData.appModels[temp_index].id)
            }
        }
        
        func copyText(){
            var text = String()
            text.append("AppKey:[\(appModel.appkey)]")
            text.append("\n")
            text.append("Client ID:[\(appModel.client_id)]")
            text.append("\n")
            text.append("ClientSecret:[\(appModel.client_secret)]")
            //https://www.jianshu.com/p/3b737ef0d275
            //必须先清空一下,否则会失败
            NSPasteboard.general.clearContents()
            let success = NSPasteboard.general.setString(text, forType: .string)
            if success {
                print("复制成功")
            }else{
                print("复制失败")
            }
        }
    }
}

#Preview {
    AppkeyListView()
}
